/**
 * class 的绑定
 *    Vue中 class 绑定是非常灵活的
 *      :class="abc"
 *      :class="abc ? 'active' : ''"
 *      :class="{ active: abc }"
 *      :class="[abc, 'abc', { active: abc }]"
 *    React 中不够灵活
 *
 * classnames 包的使用
 *    https://www.npmjs.com/package/classnames
 */

import React from "react";

// 引入 classnames
import classNames from "classnames";

class App extends React.Component {
  state = {
    isActive: false,
    tabs: [
      { id: 1, title: "Tab1" },
      { id: 2, title: "Tab2" },
      { id: 3, title: "Tab3" },
    ],
    curTabId: 1, // 当前激活的Tab的Id
    labels: [
      { id: 1, title: "刷漆" },
      { id: 2, title: "鄙人" },
      { id: 3, title: "漂亮" },
    ],
    curLabelIds: [1], // 当前高亮的 label 的 id 集合
  };

  handleTab(id, event) {
    console.log("id", id);
    console.log("event", event);
    this.setState({
      curTabId: id,
    });
  }

  handleLabel(id) {
    if (this.state.curLabelIds.includes(id)) {
      // 存在，则删除
      this.setState({
        curLabelIds: this.state.curLabelIds.filter((item) => item !== id),
      });
    } else {
      // 不存在，则增加
      this.setState({
        curLabelIds: [...this.state.curLabelIds, id],
      });
    }
  }

  render() {
    console.log("render");
    const { tabs, curTabId, labels, curLabelIds } = this.state;
    return (
      <div>
        <div>
          {labels.map((item) => {
            const str = classNames("label", {
              active: curLabelIds.includes(item.id),
            });
            return (
              <div
                key={item.id}
                className={str}
                onClick={() => this.handleLabel(item.id)}
              >
                {item.title}
              </div>
            );
          })}
        </div>

        <hr />

        {tabs.map((item) => {
          const str = classNames({ active: curTabId === item.id });

          return (
            <button
              key={item.id}
              className={str}
              onClick={this.handleTab.bind(this, item.id)}
            >
              {item.title}
            </button>
          );
        })}

        <hr />

        {/* 可以的 */}
        {/* <div className={`box ${this.state.isActive ? "active" : ""}`}></div> */}

        {/* 错误的 */}
        {/* <div className={{ box: true, active: this.state.isActive }}></div> */}

        {/* classnames 的玩法 */}
        <div
          className={classNames("box", { active: this.state.isActive })}
        ></div>
      </div>
    );
  }
}

export default App;
